﻿using ControlzEx.Theming;
using MaterialDesignThemes.Wpf;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using StudentInfoSystem.Core.Interfaces;
using StudentInfoSystem.Core.Models;
using StudentInfoSystem.UI.Services;
using StudentInfoSystem.UI.ViewModels;
using StudentInfoSystem.UI.Views.Component;
using StudentInfoSystem.UI.Views.Dialogs;
using StudentInfoSystem.UI.Views.Pages;
using StudentInfoSystem.UI.Views.Windows;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace StudentInfoSystem.UI.Views;

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{

    private readonly MainWindowViewModel _viewModel;// 视图模型
    public MainWindow()
    {
        // ======================== 前置工作 ========================

        // ======================== 前置工作 ========================

        InitializeComponent();

        // ************************ 后置初始化 ************************

        // 可以在Bootstrapper中注入依赖
        _viewModel = new MainWindowViewModel();
        DataContext = _viewModel;

        // ************************ 后置初始化 ************************
        // 监听设置变化
        AppSettings.Instance.PropertyChanged += OnAppSettingsChanged;

        // 订阅导出数据库事件
        // 订阅TitleBar的导出事件
        AppTitleBar.DatabaseExportRequested += TitleBar_DatabaseExportRequested;
    }
    private async void TitleBar_DatabaseExportRequested(object sender, (string FilePath, ExportFormat Format) args)
    {
        ProgressDialog progressDialog = null;

        try
        {
            // 显示进度指示器
            progressDialog = ProgressDialog.Show(
                title: "正在导出数据库",
                message: $"正在导出为 {args.Format} 格式...",
                canCancel: true,
                owner: this
            );

            // 处理取消请求
            progressDialog.CancelRequested += (s, e) =>
            {
                progressDialog.ReportError("导出操作已取消");

                // 使用带自动关闭的消息对话框
                MessageDialog.ShowSuccess(
                    message: "导出操作已取消",
                    title: "操作取消",
                    owner: this,
                    autoCloseSeconds: 2
                );
            };

            // 异步执行导出
            await Task.Run(() =>
            {
                var studentService = Bootstrapper.AppHost.Services.GetRequiredService<IStudentService>();
                studentService.ExportDatabase(args.FilePath, args.Format);
            });

            // 完成导出操作（会自动关闭进度对话框）
            progressDialog.Complete($"数据库已成功导出为 {args.Format} 格式!");

            // 显示成功消息（2秒后自动关闭）
            MessageDialog.ShowSuccess(
                message: $"数据库已成功导出为 {args.Format} 格式!",
                title: "导出成功",
                owner: this,
                autoCloseSeconds: 2
            );

            // 提供打开文件夹选项
            var result = await Dispatcher.InvokeAsync(() =>
                MessageBox.Show("是否打开包含导出文件的文件夹?", "导出完成",
                MessageBoxButton.YesNo, MessageBoxImage.Question)
            );

            if (result == MessageBoxResult.Yes)
            {
                try
                {
                    Process.Start("explorer.exe", $"/select,\"{args.FilePath}\"");
                }
                catch (Exception ex)
                {
                    // 错误消息也自动关闭
                    MessageDialog.ShowError(
                        message: $"无法打开文件夹:\n{ex.Message}",
                        title: "错误",
                        owner: this,
                        autoCloseSeconds: 3
                    );
                }
            }
        }
        catch (Exception ex)
        {
            progressDialog?.ReportError($"导出失败: {ex.Message}");

            // 显示错误消息（3秒后自动关闭）
            MessageDialog.ShowError(
                message: $"导出过程中发生错误:\n{ex.Message}",
                title: "导出失败",
                owner: this,
                autoCloseSeconds: 3
            );
        }
        finally
        {
            // 安全后备 - 确保进度对话框关闭
            if (progressDialog != null && progressDialog.IsLoaded)
            {
                // 确保恢复主窗口状态
                this.IsEnabled = true;
                this.Activate();

                // 等待一小段时间让自动关闭生效
                await Task.Delay(100);
                if (progressDialog.IsLoaded)
                {
                    progressDialog.Close();
                }
            }
        }
    }
    private void OnAppSettingsChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == nameof(AppSettings.IsBackgroundImageEnabled) ||
            e.PropertyName == nameof(AppSettings.BackgroundImagePath))
        {
            UpdateBackgroundImage();
        }
    }
    protected override void OnClosed(EventArgs e)
    {
        AppSettings.Instance.PropertyChanged -= OnAppSettingsChanged;
        if(AppSettings.Instance.CurrentUser != null)
        {
            if (AppSettings.Instance.CurrentUser.IsAdmin)
            {
                AppSettings.Instance.CurrentUser = null;
                AppSettings.Instance.IsAutoLogin = false;
                AppSettings.Instance.LastUsername = "";
                AppSettings.Instance.LastPassword = "";
            }
        }

        base.OnClosed(e);
    }

    // 窗体加载处理，变成真正的圆角矩形
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        UpdateWindowClip();
        // 订阅数据库路径更改事件
        AppTitleBar.DatabasePathChanged += (s, newPath) =>
        {
            // 更新设置
            AppSettings.Instance.SavedDataBasePath = newPath;
            // 通知视图模型重新加载数据
            _viewModel.ReloadData();
            // 您可能需要通过视图模型或服务来重新初始化数据库连接
            MessageBox.Show($"数据库路径已更改为: {newPath}\n需要重启应用以使更改生效",
                           "数据库路径已更新", MessageBoxButton.OK, MessageBoxImage.Information);
        };
    }
    private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        UpdateWindowClip();
    }
    private void UpdateWindowClip()
    {
        // 仅在非最大化状态下应用圆角裁剪
        if (WindowState != WindowState.Maximized)
        {
            // 创建圆角矩形几何图形
            var cornerRadius = (CornerRadius)Application.Current.Resources["WindowCornerRadius"];
            double radiusValue = cornerRadius.TopLeft;
            RectangleGeometry clipGeometry = new(
                new Rect(0, 0, ActualWidth, ActualHeight),
                radiusValue, // 圆角X半径
                radiusValue  // 圆角Y半径
            );
            Clip = clipGeometry;
        }
        else
        {
            // 最大化时移除裁剪恢复直角
            Clip = null;
        }
    }

    // 窗口拖动方法
    protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
    {
        base.OnMouseLeftButtonDown(e);
        DragMove();
    }

    // 最小化
    private void MinimizeWindow(object sender, RoutedEventArgs e)
    {
        WindowState = WindowState.Minimized;
    }

    // 最大化/还原
    private void MaximizeWindow(object sender, RoutedEventArgs e)
    {
        WindowState = WindowState == WindowState.Maximized
            ? WindowState.Normal
            : WindowState.Maximized;
    }

    // 关闭
    private void CloseWindow(object sender, RoutedEventArgs e)
    {
        Close();
    }

    // 菜单项点击处理
    private void SideMenu_MenuItemClicked(object sender, RoutedEventArgs e)
    {
        if (sender is string menuTag)
        {
            Log.Information($"Menu: {menuTag}");
            _viewModel.ExecuteNavigation(menuTag);
        }
    }

    // 添加登录请求处理函数
    private void ShowLoginWindow()
    {
        var loginWindow = new LoginWindow
        {
            IsDuringStartup = false,
            Owner = this,
            WindowStartupLocation = WindowStartupLocation.CenterOwner
        };
        loginWindow.LoginSuccess += (user) =>
        {
            loginWindow.Close();
        };
        loginWindow.ShowDialog();
    }


    // 修改原有的UserAvatar_Click方法
    private void UserAvatar_Click(object sender, RoutedEventArgs e)
    {
        if (AppSettings.Instance.CurrentUser == null)
        {
            ShowLoginWindow();
        }
    }

    // 实现INotifyPropertyChanged接口
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private void UpdateBackgroundImage()
    {
        if (!AppSettings.Instance.IsBackgroundImageEnabled)
        {
            BackgroundImageBorder.Visibility = Visibility.Collapsed;
            return;
        }

        BackgroundImageBorder.Visibility = Visibility.Visible;

        string imagePath = AppSettings.Instance.BackgroundImagePath;

        if (string.IsNullOrEmpty(imagePath))
        {
            // 使用默认背景（编译资源中的图片）
            var defaultBrush = new ImageBrush
            {
                ImageSource = new BitmapImage(new Uri("pack://application:,,,/Resources/Images/background.jpg")),
                Stretch = Stretch.UniformToFill,
                Opacity = 0.25
            };
            BackgroundImageBorder.Background = defaultBrush;
        }
        else
        {
            // 使用自定义背景
            try
            {
                var customBrush = new ImageBrush
                {
                    ImageSource = new BitmapImage(new Uri(imagePath)),
                    Stretch = Stretch.UniformToFill,
                    Opacity = 0.25
                };
                BackgroundImageBorder.Background = customBrush;
            }
            catch (Exception ex)
            {
                // 如果加载自定义背景失败，回退到默认背景
                Log.Warning(ex, "加载自定义背景失败，使用默认背景");
                var defaultBrush = new ImageBrush
                {
                    ImageSource = new BitmapImage(new Uri("pack://application:,,,/Resources/Images/background.jpg")),
                    Stretch = Stretch.UniformToFill,
                    Opacity = 0.25
                };
                BackgroundImageBorder.Background = defaultBrush;

                // 可选：通知用户
                MessageBox.Show("加载自定义背景失败，已恢复默认背景", "背景加载错误",
                               MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
    }
}

